package com.components.cachewebview

import java.io.File
import java.net.URL

class DynamicCacheLoader {
    companion object {
        @Volatile
        private var INSTANCE: DynamicCacheLoader? = null
        fun getInstance(): DynamicCacheLoader? {
            if (INSTANCE == null) {
                synchronized(DynamicCacheLoader::class.java) {
                    if (INSTANCE == null) {
                        INSTANCE = DynamicCacheLoader()
                    }
                }
            }
            return INSTANCE
        }
    }

    fun getResByUrl(file: File, url: String): File? {
        val uPath = getUrlPath(url)
        if (file.isDirectory) {
            val files = file.listFiles()
            files?.forEach {
                if (it.isDirectory) {
                    val targetFile: File? = getResByUrl(it, url)
                    if (targetFile != null) {
                        return targetFile
                    }
                } else {
                    val fileName = it.name
                    if (uPath.endsWith(fileName)) {
                        return it
                    }
                }
            }
        } else {
            val fileName = file.name
            if (uPath.endsWith(fileName)) {
                return file
            }
        }
        return null
    }

    fun getUrlPath(url: String): String {
        var uPath = ""
        val u = URL(url)
        uPath = u.path
        if (uPath.startsWith("/")) {
            if (uPath.length == 1) {
                return uPath
            }
            uPath = uPath.substring(1)
        }
        return uPath
    }

}